import { toast } from '@/components/bs-ui/toast/use-toast'
import axios from 'axios'
import i18next from 'i18next'
axios.defaults.withCredentials = true
const customAxios = axios.create({
  // 配置
})

customAxios.interceptors.response.use(
  function (response) {
    const code = response.data.status_code || response.data.code
    const message = response.data.status_message || response.data.message
    const err_msg = message || '未知异常'
    console.log('response code, message :>> ', code, message)
    if (code >= 200 && code < 300) {
      return response.data.data
    } else if (code) {
      let error_info = err_msg
      if (typeof err_msg === 'object') {
        try {
          error_info = JSON.stringify(err_msg)
        } catch (error) {
          console.error('status_message not json')
        }
      } else {
        error_info = String(err_msg)
      }
      if (error_info) {
        toast({
          title: `${i18next.t('prompt')}`,
          variant: 'error',
          description: `${error_info}`
        })
      }
    }
    return Promise.reject(err_msg)
  },
  function (error) {
    console.error('application error :>> ', error)
    if (error.response?.status === 401) {
      // cookie expires
      console.error('登录过期 :>> ')
      const UUR_INFO = 'UUR_INFO'
      const infoStr = localStorage.getItem(UUR_INFO)
      localStorage.removeItem(UUR_INFO)
      localStorage.removeItem('migu-token')

      const feMode = localStorage.getItem('fe-login-mode')
      const mode = feMode ? parseInt(feMode) : 2
      if (mode === 2) {
        location.href = localStorage.getItem('migu-back-url') || 'https://smbpaasadmin.migu.com'
        return Promise.reject(error)
      }

      infoStr && location.reload()
      return Promise.reject(error)
    }
    let message = error.response?.status ? `${error.response?.status}：${error.message}` : error.message

    if (error.response?.status === 403) {
      message = `403：暂无该功能权限，请联系企业超级管理员`
    }
    // app 弹窗
    toast({
      title: `${i18next.t('prompt')}`,
      variant: 'error',
      description: message
    })
    // window.errorAlerts([error.message])
    return Promise.reject(error)
  }
)

export default customAxios

// 接口异常提示弹窗
export function captureAndAlertRequestErrorHoc(apiFunc, iocFunc?) {
  return apiFunc.catch(error => {
    if (error === null) return // app error

    console.log('error :>> ', error)
    iocFunc?.(error)
    // 弹窗
    toast({
      title: `${i18next.t('prompt')}`,
      variant: 'error',
      description: typeof error === 'string' ? error : JSON.stringify(error)
    })
    console.error('逻辑异常 :>> ', error)
    return false
  })
}
